<?php
/**
 * 生成操作按钮
 * @param array $operate 操作按钮数组
 */
function showOperate($operate = [])
{
    if(empty($operate)){
        return '';
    }

    $option = '';
    foreach($operate as $key=>$vo){
        if(authCheck($vo['auth'])){
            $option .= ' <a href="' . $vo['href'] . '"><button type="button" class="btn btn-' . $vo['btnStyle'] . ' btn-sm">'.
                '<i class="' . $vo['icon'] . '"></i> ' . $key . '</button></a>';
        }
    }

    return $option;
}

/**
 * 将字符解析成数组
 * @param $str
 */
function parseParams($str)
{
    $arrParams = [];
    parse_str(html_entity_decode(urldecode($str)), $arrParams);
    return $arrParams;
}

/**
 * 子孙树 用于菜单整理
 * @param $param
 * @param int $pid
 */
function subTree($param, $pid = 0)
{
    static $res = [];
    foreach($param as $key=>$vo){

        if( $pid == $vo['pid'] ){
            $res[] = $vo;
            subTree($param, $vo['id']);
        }
    }

    return $res;
}

/**
 * 整理菜单住方法
 * @param $param
 * @return array
 */
function prepareMenu($param)
{
    $param = objToArray($param);
    $parent = []; //父类
    $child = [];  //子类

    foreach($param as $key=>$vo){

        if(0 == $vo['type_id']){
            $vo['href'] = '#';
            $parent[] = $vo;
        }else{
            $vo['href'] = url($vo['control_name'] .'/'. $vo['action_name']); //跳转地址
            $child[] = $vo;
        }
    }

    foreach($parent as $key=>$vo){
        foreach($child as $k=>$v){

            if($v['type_id'] == $vo['id']){
                $parent[$key]['child'][] = $v;
            }
        }
    }
    unset($child);

    return $parent;
}

/**
 * 解析备份sql文件
 * @param $file
 */
function analysisSql($file)
{
    // sql文件包含的sql语句数组
    $sqls = array ();
    $f = fopen ( $file, "rb" );
    // 创建表缓冲变量
    $create = '';
    while ( ! feof ( $f ) ) {
        // 读取每一行sql
        $line = fgets ( $f );
        // 如果包含空白行，则跳过
        if (trim ( $line ) == '') {
            continue;
        }
        // 如果结尾包含';'(即为一个完整的sql语句，这里是插入语句)，并且不包含'ENGINE='(即创建表的最后一句)，
        if (! preg_match ( '/;/', $line, $match ) || preg_match ( '/ENGINE=/', $line, $match )) {
            // 将本次sql语句与创建表sql连接存起来
            $create .= $line;
            // 如果包含了创建表的最后一句
            if (preg_match ( '/ENGINE=/', $create, $match )) {
                // 则将其合并到sql数组
                $sqls [] = $create;
                // 清空当前，准备下一个表的创建
                $create = '';
            }
            // 跳过本次
            continue;
        }

        $sqls [] = $line;
    }
    fclose ( $f );

    return $sqls;
}

/**
 * 统一返回信息
 * @param $code
 * @param $data
 * @param $msge
 */
function msg($code, $data, $msg)
{
    return compact('code', 'data', 'msg');
}

/**
 * 对象转换成数组
 * @param $obj
 */
function objToArray($obj)
{
    return json_decode(json_encode($obj), true);
}

/**
 * 权限检测
 * @param $rule
 */
function authCheck($rule)
{
    $control = explode('/', $rule)['0'];
    if(in_array($control, ['login', 'index'])){
        return true;
    }

    if(in_array($rule, session('action'))){
        return true;
    }

    return false;
}

/**
 * 整理出tree数据 ---  layui tree
 * @param $pInfo
 * @param $spread
 */
function getTree($pInfo, $spread = true)
{

    $res = [];
    $tree = [];
    //整理数组
    foreach($pInfo as $key=>$vo){

        if($spread){
            $vo['spread'] = true;  //默认展开
        }
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($pInfo);

    //查找子孙
    foreach($res as $key=>$vo){
        if(0 != $vo['pid']){
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    //过滤杂质
    foreach( $res as $key=>$vo ){
        if(0 == $vo['pid']){
            $tree[] = $vo;
        }
    }
    unset( $res );

    return $tree;
}

/**
 * [将数据整理成一维]
 */
function changeArrTo1D ($arr,$res = []){
	foreach($arr as $v){
		if(is_array($v)){
			$res = changeArrTo1D($v,$res);
		}else{
			$res[] = $v;
		}
	}
	return $res;
}

/**
 * [一维数组转树]
 */
function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'children') {
	$tree = $map = [];
	$map = array_column($list,null,$id);
	foreach ($list as $item) {
		if (isset($item[$pid]) && isset($map[$item[$pid]])) {
			$map[$item[$pid]][$son][] = &$map[$item[$id]];
		} else {
			$tree[] = &$map[$item[$id]];
		}
	}
	unset($map);
	return $tree;
}

function getNameByTree($tree,$res=[],$prefix = ''){
	$str = '| - ';
	foreach($tree as $v){
		$res[] = [
			'id'=>$v['id'],
			'name'=>$str.$prefix.$v['name']
		];
		if(!empty($v['children'])){
			$prefix .= '- - ';
			$res = getNameByTree($v['children'],$res,$prefix);
			$prefix = mb_substr($prefix,4,mb_strlen($prefix));
		}
	}
	return $res;
}

/**
 * [消息编码]
 * @param $userInfo = ['head' => string,'real_name' => string,'id'=> string]
 */
function socketMsg_encode($send_id="",$userInfo=[],$msg="") {
	$xml = '<msg class="user_id_'.$send_id.'">';
		$xml .='<img class="user-head" src="'.$userInfo['head'].'"/>';
		$xml .='<name>'.$userInfo['real_name'].'</name>';
		$xml .='<time>'.date("Y-m-d H:i").'</time>';
		$xml .='<ct>'.$msg.'</ct>';
	$xml .='</msg>';
	return $xml;
}
/**
 * [消息解码]
 */
function socketMsg_decode($xml) {
	return [];
}

/**
 * [推送socket消息]
 * @param $uid_str = "1,2,3,4..."
 * @param $msg string
 * @param $userInfo = ['head'=>string,'real_name'=>string,'id'=>string,'msg_name'=>string]
 */
function send_socket_msg($uid_str,$msg,$msgInfo) {
	// 推送
	$uid_arr = explode(",",$uid_str);
	$bool = true;
	$error_ids = [];
	foreach($uid_arr as $v){
		// 建立socket连接到内部推送端口
		$client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
		// 推送的数据，包含uid字段，表示是给这个uid推送
		$data = ['uid'=>"uid:".$v, 'msg'=>$msg,'info'=>$msgInfo];
		// 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
		fwrite($client, json_encode($data)."\n");
		// 读取推送结果
		$res = fread($client, 8192);
		if($res != "ok\n"){
			$bool = false;
			$error_ids[] = $v;
		}
	}
	// 推送结果
	if($bool){
		return ['code'=>1,'msg'=>'success'];
	}else{
		return ['code'=>0,'msg'=>'fail:'.implode(",",$error_ids)];
	}
}

/**
 * [判断是否为移动端访问]
 */
function isMobile() {
	if(isset($_SERVER['HTTP_X_WAP_PROFILE'])){
		return true;
	}
	if(isset($_SERVER['HTTP_VIA'])){
		return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
	}
	if (isset($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = [
			'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp',
			'sie-','philips','panasonic','alcatel','lenovo','iphone','ipod',
			'blackberry','meizu','android','netfront','symbian','ucweb','windowsce',
			'palm','operamini','operamobi','openwave','nexusone','cldc',
			'midp','wap','mobile','MicroMessenger'
		];
		$rules = "/(" . implode('|', $clientkeywords) . ")/i";
		if (preg_match($rules, strtolower($_SERVER['HTTP_USER_AGENT']))){
		  	return true;
		}
	}
	if (isset ($_SERVER['HTTP_ACCEPT'])) {
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}
